//
//  QXAdHandler.m
//  iAccountBook
//
//  Created by 侯伟 on 2021/9/5.
//

#import "QXAdHandler.h"
#import <AdSupport/AdSupport.h>
#import <AFNetworking/AFNetworking.h>
#import <YYModel/YYModel.h>

#import "QXAdvert.h"
#import "QXConfig.h"


@interface QXAdHandler ()

@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end



@implementation QXAdHandler


+ (QXAdHandler *)shareHander{
    static dispatch_once_t onece;
    static QXAdHandler *share = NULL;
    dispatch_once(&onece, ^{
        share = [[self alloc] init];
    });
    return share;
}

- (instancetype)init{
    if (self = [super init]){
        [self initManager];
    }
    return self;
}

- (void)initManager{
    
    AFHTTPSessionManager* _manager = [AFHTTPSessionManager manager];
    
    ///config
    NSURLSessionConfiguration* _config = _manager.session.configuration;
    _config.timeoutIntervalForRequest = 3.f;
    _config.timeoutIntervalForResource = 3.f;
    _config.requestCachePolicy  = NSURLRequestReturnCacheDataElseLoad;
    _config.HTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    ///request
    AFJSONRequestSerializer* requestSerializer = [AFJSONRequestSerializer serializer];
    _manager.requestSerializer = requestSerializer;
    
    ///response
    AFJSONResponseSerializer* responseSerializer = [AFJSONResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"text/xml",@"image/jpeg",@"image/png", @"application/octet-stream", @"multipart/form-data",@"text/plain",nil];
    _manager.responseSerializer = responseSerializer;
    
    
    ///securityPolicy
    AFSecurityPolicy* securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    _manager.securityPolicy = securityPolicy;
    
    self.manager = _manager;
}

- (void)request:(NSString *)url params:(NSDictionary *)params success:(void(^)(id response))success failure:(void(^)(NSError* error))failure{
    
    if(!url) return;

    [self.manager GET:url parameters:params headers:@{@"User-Agent":[self getUserAgent]} progress:NULL success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if(success){
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(failure){
            failure(error);
        }
    }];
}


/// 获取广告渠道
/// @param adType 类型
/// @param block 回调
- (void)requestAdChannelWithAdType:(ADType)adType block:(AdTypeResponse)block{
    
    NSString* url = @"http://api.quxingwuxian.com/sdk";
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    
    NSString* idfa  = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    if(idfa){
        [params setValue:idfa forKey:@"idfa"];
    }
    
    QXConfig* config = [QXConfig defaultConfig];
    if(config.appid){
        [params setValue:config.appid forKey:@"appid"];
    }
    NSString* codeid;
    NSString* type;
    if(adType == ADType_Splash){
        codeid = config.sAdId;
        type = @"3";
    }else if (adType == ADType_Video){
        codeid = config.vAdId;
        type = @"6";
    }else if (adType == ADType_Banner){
        codeid = config.bAdId;
        type = @"4";
    }
    
    if(codeid){
        [params setValue:codeid forKey:@"codeid"];
    }
    [params setValue:type forKey:@"type"];


    [[QXAdHandler shareHander] request:url params:params success:^(id  _Nonnull response) {
        NSLog(@"广告类型：%@",response);
        if(!response) return;
        
        int code = [response[@"code"] intValue];
        if(1 == code){
            ADChannel channel = [response[@"sdk"] intValue];
            if(block){
                block(channel);
            }
        }else{
            if(block){
                block(ADChannelNO);
            }
        }
    }failure:^(NSError * _Nonnull error) {
        if(block){
            block(ADChannelNO);
        }
    }];
}

/// 获取自有广告
/// @param adType 类型
/// @param block 回调
- (void)requestQXAdWithAdType:(ADType)adType block:(AdvertResponse)block{
    

    NSString* url = @"http://api.quxingwuxian.com/request";
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    
    NSString* idfa  = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    if(idfa){
        [params setValue:idfa forKey:@"idfa"];
    }
    
    QXConfig* config = [QXConfig defaultConfig];
    if(config.appid){
        [params setValue:config.appid forKey:@"appid"];
    }
    NSString* codeid;
    NSString* type;
    if(adType == ADType_Splash){
        codeid = config.sAdId;
        type = @"3";
    }else if (adType == ADType_Video){
        codeid = config.vAdId;
        type = @"6";
    }else if (adType == ADType_Banner){
        codeid = config.bAdId;
        type = @"4";
    }
    
    if(codeid){
        [params setValue:codeid forKey:@"codeid"];
    }
    [params setValue:type forKey:@"type"];
    
    
    [self request:url params:params success:^(id  _Nonnull response) {
        NSLog(@"自己的广告：%@",response);
        if(!response) return;
        
        int code = [response[@"code"] intValue];
        
        if(1 == code){
            NSArray *adDatas = [NSArray yy_modelArrayWithClass:QXAdvert.class json:response[@"ad"]];
            if(!adDatas.count){
                if(block){
                    block(NULL);
                }
                return;
            }
            QXAdvert* advert = adDatas.firstObject;
            if(block){
                block(advert);
            }
        }else{
            if(block){
                block(NULL);
            }
        }
    }failure:^(NSError * _Nonnull error) {
        if(block){
            block(NULL);
        }
    }];
}


/// 自有广告点击回调
- (void)selfAdClickCallBack:(NSString*)url{
    [self request:url params:@{} success:NULL failure:NULL];
}

/// 自有广告显示回调
- (void)selfAdShowCallBack:(NSString*)url{
    [self request:url params:@{} success:NULL failure:NULL];
}


- (void)adCallBackAdType:(ADType)adType config:(QXConfig*)config type:(NSInteger)type{
    
    NSString* url = @"http://api.quxingwuxian.com/sdks";
    
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    
    NSString* idfa  = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    if(idfa){
        [params setValue:idfa forKey:@"aid"];
    }
    if(config.channel == ADChannelCSJ){
        [params setValue:@"csj" forKey:@"qdid"];
    }else if (config.channel == ADChannelYLH){
        [params setValue:@"ylh" forKey:@"qdid"];
    }
    
    [params setValue:[QXConfig defaultConfig].appid forKey:@"appid"];
    
    NSString* codeid;
    NSString* codeids;
    if(adType == ADType_Splash){
        codeid = [QXConfig defaultConfig].sAdId;
        codeids = config.sAdId;
    }else if (adType == ADType_Video){
        codeid = [QXConfig defaultConfig].vAdId;
        codeids = config.vAdId;
    }else if (adType == ADType_Banner){
        codeid = [QXConfig defaultConfig].bAdId;
        codeids = config.bAdId;
    }
    
    if(codeid){
        [params setValue:codeid forKey:@"codeid"];
    }
    if(codeids){
        [params setValue:codeids forKey:@"codeids"];
    }
    
    [params setValue:@(type) forKey:@"type"];
    
    [self request:url params:params success:^(id response) {
        
    } failure:^(NSError *error) {
        
    }];
}

- (NSString*)getUserAgent{
    NSString * userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]];
    return userAgent;
}
@end
